-- Author: chleniang@163.com

local config = require("config")

local _M = {}

local mt = {
    __index = _M
}

_M.set = function(self, key, value, timeout)
    local ok, err = nil, nil
    if timeout and timeout > 0 then
        ok, err = self.rediscli:setex(key, timeout, value)
        if not ok then
            ngx.log(ngx.ERR, "[easy_waf] redis SETEX failed: " .. tostring(err))
            return
        end
    else
        ok, err = self.rediscli:set(key, value)
        if not ok then
            ngx.log(ngx.ERR, "[easy_waf] redis SET failed: " .. tostring(err))
            return
        end
    end
    return ok
end

_M.incr = function(self, key)
    local ok, err = self.rediscli:incr(key)
    if not ok then
        ngx.log(ngx.ERR, "[easy_waf] redis INCR failed: " .. tostring(err))
        return
    end
    return ok
end

_M.get = function(self, key)
    local res, err = self.rediscli:get(key)
    if not res then
        return
    end

    if res == ngx.null then
        -- not found
        return
    end
    return res
end

_M.set_ccip = function(self, ip, timeout)
    local ipkey = g_ccip_prefix .. ip
    local ok, err = nil, nil
    if timeout > 0 then
        ok, err = self.rediscli:setex(ipkey, timeout, 1)
        if not ok then
            ngx.log(ngx.ERR, "[easy_waf] redis SETEX failed: " .. tostring(err))
            return
        end
    else
        ok, err = self.rediscli:set(ipkey, 1)
        if not ok then
            ngx.log(ngx.ERR, "[easy_waf] redis SET failed: " .. tostring(err))
            return
        end
    end
    return ok
end

_M.ccip_exist = function(self, ip)
    local ipkey = g_ccip_prefix .. ip
    local res, err = self.rediscli:get(ipkey)
    if not res then
        return false
    end

    if res == ngx.null then
        -- not found
        return false
    end

    return true
end

_M.clean_ccip = function(self, ip)
    local ipkey
    if (not ip) or (ip == "all") then
        -- ip = nil 等同于 “all", 清除所有 CC 拦截的ip
        ipkey = g_ccip_prefix .. "*"
    else
        -- 清除指定IP
        ipkey = g_ccip_prefix .. ip
    end
    local all_keys = self.rediscli:keys(ipkey)
    for _, key in pairs(all_keys) do
        self.rediscli:del(key)
    end
end

_M.new = function()
    local host = config.redis_host or "127.0.0.1"
    local port = config.redis_port or 6379
    local pwd = config.redis_password or ""
    local db_index = config.redis_db_index or 0

    local cls_redis = require("lib.cls_redis")
    local self = {
        rediscli = cls_redis:new({
            host = host,
            port = port,
            db_index = db_index,
            password = pwd
        })
    }
    return setmetatable(self, mt)
end

return _M
